package com.steven.sync;

import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.LongAdder;


/**
 * sys: 使用同步锁
 * atomic :无锁cas操作，或者说是自旋锁
 * LongAdder：分段式锁 内部也是CAS自旋锁，并发高的情况下，使用该类回快一些
 */
public class CountZiZeng_test {

    
    static long count1 = 0L;
    static AtomicLong count2  = new AtomicLong(0L);
    static LongAdder count3 = new LongAdder();

    public static void main(String[] args) throws Exception {
        
        Thread[] threads = new Thread[10000];
        Object lock = new Object();
        for (int i = 0; i <threads.length; i++) {
            threads[i]= new Thread(() -> {
                for (int j = 0; j < 100000; j++) {
                    synchronized (lock){
                        count1++;
                    }
                }
            });
        }
        long start1 = System.currentTimeMillis();

        for (int i = 0; i < threads.length; i++) {
            threads[i].start();
        }
        for (int i = 0; i < threads.length; i++) {
            threads[i].join();
        }
        long end1 = System.currentTimeMillis();
        System.out.println("count："+(end1-start1));


        for (int i = 0; i < threads.length; i++) {
            threads[i] =new Thread(()->{
                for (int j = 0; j < 100000; j++) {
                    count2.incrementAndGet();
                }
            });
        }
        long start = System.currentTimeMillis();

        for (int i = 0; i < threads.length; i++) {
            threads[i].start();
        }
        for (int i = 0; i < threads.length; i++) {
            threads[i].join();
        }
        long end = System.currentTimeMillis();
        System.out.println("automic："+(end-start));


        for (int i = 0; i < threads.length; i++) {
            threads[i] =new Thread(()->{
                for (int j = 0; j < 100000; j++) {
                    count3.increment();
                }
            });
        }
        long start3 = System.currentTimeMillis();

        for (int i = 0; i < threads.length; i++) {
            threads[i].start();
        }
        for (int i = 0; i < threads.length; i++) {
            threads[i].join();
        }
        long end3 = System.currentTimeMillis();
        System.out.println("adder："+(end3-start3));



    }

}
